//
//  KZTimerView.m
//  听说弱点强化训练
//
//  Created by 朱凯 on 2018/9/3.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "KZTimerView.h"

#import "KZTimerMomentView.h"       // 时刻：00:00
#import "KZTimerPausingView.h"      // 暂停中

@implementation KZTimerView
{
    KZTimerMomentView *_momentView; // 时刻
    CAShapeLayer *_arcLayer;        // 弧状layer
    
    BOOL _pausing;                  // 是否暂停中
    NSTimer *_timer;                // 定时器
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        
        _pausing = false;
        [self setupUI];
        [self addTarget:self action:@selector(onClick:) forControlEvents:UIControlEventTouchUpInside];
        
        // 注册进入后台通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onApplicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil];
    }
    return self;
}

#pragma mark - 创建视图
- (void)setupUI {
    
    _arcLayer = [CAShapeLayer layer];
    _arcLayer.lineWidth = 1;
    _arcLayer.fillColor = UIColor.clearColor.CGColor;
    _arcLayer.strokeColor = UIColor.whiteColor.CGColor;
    [self.layer addSublayer:_arcLayer];
    
    CGFloat r = self.height / 2 * 0.8;
    CGFloat cx = self.width / 2;
    CGFloat cy = self.height / 2;
    CGFloat angle = M_PI / 4;
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(cx - r * sin(angle), cy - r * cos(angle))];
    [path addArcWithCenter:CGPointMake(cx, cy) radius:r startAngle:M_PI * 1.5 - angle endAngle:M_PI * 1.5 + angle clockwise:true];
    [path moveToPoint:CGPointMake(cx + r * sin(angle), cy + r * cos(angle))];
    [path addArcWithCenter:CGPointMake(cx, cy) radius:r startAngle:M_PI * 0.5 - angle endAngle:M_PI * 0.5 + angle clockwise:true];
    _arcLayer.path = path.CGPath;
    
    // 时刻视图
    _momentView = [[KZTimerMomentView alloc] initWithFrame:self.bounds];
    [self addSubview:_momentView];
}

#pragma mark - 事件
- (void)onClick:(UIControl *)sender {
    // 暂停中，则恢复；否则暂停
    if (_pausing) {
        [self resume];
    } else {
        [self pause:true];
    }
}
- (void)onApplicationWillResignActive {
    // 如果暂停中，则不需要操作
    if (!_pausing) {
        [self pause:true];
    }
}
#pragma mark - 定时器
- (void)addTimer {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTime) userInfo:nil repeats:true];
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
- (void)onTime {
    // 设置时刻
    _momentView.second = _second++;
}

#pragma mark - 可调用方法
- (void)start:(NSUInteger)second {
    
    // 设置秒数
    _second = second;
    // 开启定时器
    [self addTimer];
    // 设置为可交互（相对于停止后不可交互）
    self.userInteractionEnabled = true;
}

- (void)stop {
    
    // 停止时先调用暂停
    [self pause:false];
    // 关闭定时器
    [_timer invalidate];
    _timer = nil;
    // 关闭交互
    self.userInteractionEnabled = false;
}
// 暂停
- (void)pause:(BOOL)showPausingView {
    
    // 暂停定时器
    [_timer setFireDate:[NSDate distantFuture]];
    // 设置为暂停
    _pausing = true;
    // 回调
    self.onTimerStatusChanged(_pausing);
    // 展示暂停视图
    if (showPausingView) {
        [self showPausingView];
    }
}
// 恢复
- (void)resume {
    
    // 开启定时器
    [_timer setFireDate:[NSDate date]];
    // 设置为非暂停
    _pausing = false;
    // 回调
    self.onTimerStatusChanged(_pausing);
}


#pragma mark - 辅助方法
- (void)showPausingView {
    
    KZTimerPausingView *pausingView = [KZTimerPausingView new];
    [pausingView show:_associatedView];
    pausingView.onClickGoon = ^{
        [self resume];
    };
}

@end
